extends MoveStateResource


class_name AroundStateResource
"""
发射后环绕目标转圈
"""


## 顺时针环绕中心点的方向偏移
@export_range(-180, 180, 1, "degrees") var around_angle: int = 90
## 环绕半径
@export var around_radius: float = 0
## 向圆心移动的角速度
@export var inward_velocity: float = 0
## 环绕时是否面向目标
@export var is_face_to_center: bool = false
## 是否顺时针
@export var is_reverse_around: bool = false
## 最大的环绕角度
@export_range(0, 3600, 1, "radians_as_degrees
") var max_around_angle: float = TAU


func direction_to_target(ctrl: MoveController, data: Dictionary) -> Vector2:
    return (ctrl.move_component.wrapper.position - data.target_position).normalized()

func distance_to_target(ctrl: MoveController, data: Dictionary) -> float:
    return ctrl.move_component.wrapper.position.distance_to(data.target_position)

func enter(ctrl: MoveController, data: Dictionary) -> void:
    var move: MoveComponent = ctrl.move_component
    var angle: float = deg_to_rad(around_angle)
    var around_center: Vector2 = move.direction.rotated(angle) * around_radius
    data.target_position = move.wrapper.position - around_center
    data.start_direction = direction_to_target(ctrl, data).orthogonal()
    data.radius = distance_to_target(ctrl, data)
    data.around_angle = 0.0
    var is_clockwise: bool = around_angle > 0
    data.is_clockwise = not is_clockwise if is_reverse_around else is_clockwise

func update(ctrl: MoveController, data: Dictionary, delta: float, duration: float) -> bool:
    # 在圆上根据弦长计算圆心弧度
    var r: float = data.radius if is_zero_approx(inward_velocity) else direction_to_target(ctrl, data)
    if is_zero_approx(r):
        return true
    data.around_angle += ctrl.move_component.speed * delta / r
    if data.around_angle > max_around_angle:
        return true
    if is_face_to_center:
        ctrl.move_component.wrapper.global_rotation = direction_to_target(ctrl, data).angle()
    var next_direction: Vector2 = Vector2.ZERO
    var next_angle: float = data.around_angle + inward_velocity * delta
    if data.is_clockwise:
        next_direction = data.start_direction.rotated(next_angle).normalized()
    else:
        next_direction = data.start_direction.rotated(-next_angle).normalized()
        next_direction = next_direction.rotated(PI)
    ctrl.move_component.direction = next_direction
    return false

func exit(ctrl: MoveController, data: Dictionary) -> void:
    if is_face_to_center:
        ctrl.move_component.wrapper.global_rotation = ctrl.move_component.direction.angle()
